package xworker.swt.dataObject.datastore;

import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.widgets.TableItem;
import xworker.dataObject.DataObject;
import xworker.dataObject.DataObjectListener;
import xworker.lang.task.DelayTask;

public class TableDataStoreDataObjectListener extends DelayTask implements DataObjectListener, DisposeListener {
    TableDataStoreListener tableDataStoreListener;
    TableItem tableItem;
    DataObject dataObject;

    public TableDataStoreDataObjectListener(TableDataStoreListener tableDataStoreListener, DataObject dataObject, TableItem tableItem) {
        super(300);

        this.tableDataStoreListener = tableDataStoreListener;
        this.tableItem = tableItem;
        this.dataObject = dataObject;
        this.tableItem.addDisposeListener(this);

        dataObject.addListener(this);
    }

    @Override
    public void run() {
        if (!tableItem.isDisposed()) {
            tableItem.getDisplay().asyncExec(() -> {
                try {
                    tableDataStoreListener.updateItem(tableItem, dataObject, tableDataStoreListener.getActionContext());
                } catch (Exception ignored) {
                }
            });
        }
    }

    @Override
    public void changed(DataObject dataObject) {
        this.doTask();
    }

    @Override
    public void widgetDisposed(DisposeEvent event) {
        dataObject.removeListener(this);
    }
}

